﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FreedomERP.Dao.Inv;
using FreedomERP.Models;
using FreedomERP.Comm;
using FreedomERP.Dao.Inv.Impl;
using FreedomERP.Models.Inv;
using FreedomERP.Comm.Utils;
using FreedomERP.Dao.Bd.Impl;
using FreedomERP.Dao.Bd;
using System.IO;
using FreedomERP.Services.Bd;
using FreedomERP.Services.Bd.Impl;

namespace FreedomERP.Services.Inv.Impl
{
    /// <summary>
    /// 收货单管理业务层实现类
    /// 作者：梁建东
    /// </summary>
    public class InvReceiveOrderServiceImpl:IInvReceiveOrderService
    {
        IInvReceiveOrderDAO receiveOrderDAO = new InvReceiveOrderDAOImpl();
        IInvReceiveOrderDetailDAO receiveOrderDetailDAO = new InvReceiveOrderDetailDAOImpl();
        IBdCategoryDao categoryDao = new BdCategoryDaoImpl();

        /// <summary>
        /// 根据条件获取收货单列表
        /// 作者：梁建东
        /// </summary>
        public List<InvReceiveOrder> QueryReceiveOrderPaggingByParam(PagingParams paggingParams, out int totalCount)
        {
            return receiveOrderDAO.QueryReceiveOrderPaggingByParam(paggingParams, out totalCount);
        }

        /// <summary>
        /// 根据FId获取收货单
        /// 作者：梁建东
        /// </summary>
        public InvReceiveOrder GetReceiveOrderByFId(String FId)
        {
            return receiveOrderDAO.GetReceiveOrderByFId(FId);
        }

        /// <summary>
        /// 添加收货单
        /// 作者：梁建东
        /// </summary>
        public void AddReceiveOrder(InvReceiveOrderView receiveOrderView, string currAccountFId, out string FId)
        {
            InvReceiveOrder receiveOrder = new InvReceiveOrder();
            receiveOrder.FId = GuidUtils.getGuid();
            receiveOrder.FNumber = ConstData.RECEIVE_ORDER_NUMBER_HEAD + DateUtils.GetCurDateFormat("yyyyMMddHHmmss");
            receiveOrder.FName = receiveOrder.FNumber;
            receiveOrder.FBillDate = DateUtils.ParseStringToDateTime(receiveOrderView.FBillDate);
            receiveOrder.FCreateTime = DateUtils.GetCurDate();
            receiveOrder.FCreatorId = currAccountFId;
            receiveOrder.FModifyTime = DateUtils.GetCurDate();
            receiveOrder.FModifierId = currAccountFId;
            receiveOrder.FRemark = receiveOrderView.FRemark;
            receiveOrder.FOrgunitId = receiveOrderView.FOrgunitId;
            receiveOrder.FStatusId = receiveOrderView.FStatus;

            if (receiveOrderView.FDetails != null)
            {
                foreach (InvReceiveOrderDetailView detailView in receiveOrderView.FDetails)
                {
                    InvReceiveOrderDetail detail = new InvReceiveOrderDetail();
                    detail.FId = GuidUtils.getGuid();
                    detail.FProductId = detailView.FProductId;
                    detail.FNumber = detailView.FNumber;
                    detail.FPrice = detailView.FPrice;
                    detail.FAmount = detailView.FAmount;
                    detail.FRemark = detailView.FRemark;

                    receiveOrder.InvReceiveOrderDetail.Add(detail);
                }
            }

            receiveOrderDAO.AddReceiveOrder(receiveOrder);
            receiveOrderDAO.Save();

            FId = receiveOrder.FId;
        }

        /// <summary>
        /// 修改收货单
        /// 作者：梁建东
        /// </summary>
        public void ModifyReceiveOrder(InvReceiveOrderView receiveOrderView, string currAccountFId)
        {
            InvReceiveOrder objOld = receiveOrderDAO.GetReceiveOrderByFId(receiveOrderView.FId);

            if (objOld.BdCategory != null && objOld.BdCategory.FNumber.Equals(ConstData.CATEGORY_RECEIVE_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.RECEIVE_ORDER_MODIFY_ERROR);
            }

            if (objOld != null) 
            {
                objOld.FNumber = receiveOrderView.FNumber;
                objOld.FName = objOld.FNumber;
                objOld.FBillDate = DateUtils.ParseStringToDateTime(receiveOrderView.FBillDate);
                objOld.FModifyTime = DateUtils.GetCurDate();
                objOld.FModifierId = currAccountFId;
                objOld.FRemark = receiveOrderView.FRemark;
                objOld.FStatusId = receiveOrderView.FStatus;

                //判断是否删除明细
                List<InvReceiveOrderDetail> deleteList = new List<InvReceiveOrderDetail>();
                if (objOld.InvReceiveOrderDetail != null)
                {
                    foreach (InvReceiveOrderDetail detail in objOld.InvReceiveOrderDetail)
                    {
                        if (receiveOrderView.FDetails != null)
                        {
                            bool flag = false;
                            foreach (InvReceiveOrderDetailView detailView in receiveOrderView.FDetails)
                            {
                                if (detail.FId.Equals(detailView.FId))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag) 
                            {
                                deleteList.Add(detail);
                            }
                        }
                    }
                }

                //添加或修改明细
                if (receiveOrderView.FDetails != null)
                {
                    foreach (InvReceiveOrderDetailView detailView in receiveOrderView.FDetails)
                    {
                        if (objOld.InvReceiveOrderDetail!=null && detailView.FId != null && !detailView.FId.Trim().Equals("") && !detailView.FId.Trim().Equals("-1"))
                        {
                            var query = (from d in objOld.InvReceiveOrderDetail where d.FId == detailView.FId select d).ToList<InvReceiveOrderDetail>();
                            if (query != null && query.Count > 0)
                            {
                                InvReceiveOrderDetail detailOld = query.First<InvReceiveOrderDetail>();
                                detailOld.FProductId = detailView.FProductId;
                                detailOld.FNumber = detailView.FNumber;
                                detailOld.FPrice = detailView.FPrice;
                                detailOld.FAmount = detailView.FAmount;
                                detailOld.FRemark = detailView.FRemark;
                            }
                            else 
                            {
                                InvReceiveOrderDetail detail = new InvReceiveOrderDetail();
                                detail.FId = GuidUtils.getGuid();
                                detail.FProductId = detailView.FProductId;
                                detail.FNumber = detailView.FNumber;
                                detail.FPrice = detailView.FPrice;
                                detail.FAmount = detailView.FAmount;
                                detail.FRemark = detailView.FRemark;

                                objOld.InvReceiveOrderDetail.Add(detail);
                            }
                        }
                        else
                        {
                            InvReceiveOrderDetail detail = new InvReceiveOrderDetail();
                            detail.FId = GuidUtils.getGuid();
                            detail.FProductId = detailView.FProductId;
                            detail.FNumber = detailView.FNumber;
                            detail.FPrice = detailView.FPrice;
                            detail.FAmount = detailView.FAmount;
                            detail.FRemark = detailView.FRemark;

                            objOld.InvReceiveOrderDetail.Add(detail);
                        }
                    }
                }

                //删除明细
                foreach (InvReceiveOrderDetail objDelete in deleteList) 
                {
                    objOld.InvReceiveOrderDetail.Remove(objDelete);
                }

                receiveOrderDAO.Save();
            }
        }

        /// <summary>
        /// 删除收货单
        /// 作者：梁建东
        /// </summary>
        public void DeleteReceiveOrder(string FId)
        {
            InvReceiveOrder receiveOrder = receiveOrderDAO.GetReceiveOrderByFId(FId);

            if (receiveOrder.BdCategory != null && receiveOrder.BdCategory.FNumber.Equals(ConstData.CATEGORY_RECEIVE_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.RECEIVE_ORDER_DELETE_ERROR);
            }

            if (receiveOrder != null)
            {
                receiveOrderDAO.DeleteReceiveOrder(receiveOrder);
                receiveOrderDAO.Save();
            }
        }

        /// <summary>
        /// 根据FParentId获取明细列表
        /// 作者：梁建东
        /// </summary>
        public List<InvReceiveOrderDetail> GetReceiveOrderDetailListByFParentId(string FParentId)
        {
            return receiveOrderDetailDAO.GetReceiveOrderDetailListByFParentId(FParentId);
        }

        /// <summary>
        /// 审核收货单
        /// 作者：梁建东
        /// </summary>
        public void ApproveReceiveOrder(string FId, string currAccountFId)
        {
            InvReceiveOrder receiveOrder = receiveOrderDAO.GetReceiveOrderByFId(FId);

            if (receiveOrder.BdCategory != null && receiveOrder.BdCategory.FNumber.Equals(ConstData.CATEGORY_RECEIVE_ORDER_STATUS_APPROVE)) 
            {
                throw new Exception(ConstNoteMessage.RECEIVE_ORDER_APPROVE_ERROR);    
            }

            if (receiveOrder != null)
            {
                if (receiveOrder.InvReceiveOrderDetail != null)
                {
                    foreach (InvReceiveOrderDetail detail in receiveOrder.InvReceiveOrderDetail)
                    {
                        BdProduct product = detail.BdProduct;
                        product.FQty += detail.FNumber;
                    }
                }
                receiveOrder.FStatusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_RECEIVE_ORDER_STATUS, ConstData.CATEGORY_RECEIVE_ORDER_STATUS_APPROVE);
                receiveOrder.FApproveTime = DateUtils.GetCurDate();
                receiveOrder.FApproverId = currAccountFId;
                receiveOrderDAO.Save();
            }
        }

        /// <summary>
        /// 反审核收货单
        /// 作者：梁建东
        /// </summary>
        public void UnApproveReceiveOrder(string FId, string currAccountFId)
        {
            InvReceiveOrder receiveOrder = receiveOrderDAO.GetReceiveOrderByFId(FId);
            if (receiveOrder.BdCategory != null && !receiveOrder.BdCategory.FNumber.Equals(ConstData.CATEGORY_RECEIVE_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.RECEIVE_ORDER_UNAPPROVE_ERROR);
            }
            if (receiveOrder != null)
            {
                if (receiveOrder.InvReceiveOrderDetail != null)
                {
                    foreach (InvReceiveOrderDetail detail in receiveOrder.InvReceiveOrderDetail)
                    {
                        BdProduct product = detail.BdProduct;
                        product.FQty -= detail.FNumber;
                    }
                }
                receiveOrder.FStatusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_RECEIVE_ORDER_STATUS, ConstData.CATEGORY_RECEIVE_ORDER_STATUS_SAVE);
                receiveOrder.FApproveTime = null;
                receiveOrder.FApproverId = null;
                receiveOrderDAO.Save();
            }
        }

        /// <summary>
        /// 打印条码
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        /*public void PrintBarcode(string FId, string serverPath, HttpResponseBase response)
        {
            InvReceiveOrder receiveOrder = receiveOrderDAO.GetReceiveOrderByFId(FId);
            if (receiveOrder != null && receiveOrder.InvReceiveOrderDetail != null && receiveOrder.InvReceiveOrderDetail.Count>0)
            {
                string saveFilePath = @"" + serverPath + "Upload\\Barcode\\";
                string fileName = "barcode_" + receiveOrder.FNumber + ".pdf";
                if (!File.Exists(saveFilePath + fileName))
                {
                    List<BdBarcodeStore> barcodeList = new List<BdBarcodeStore>();
                    foreach (InvReceiveOrderDetail receiveDetail in receiveOrder.InvReceiveOrderDetail)
                    {
                        for (int i = 1; i <= receiveDetail.FNumber; i++)
                        {
                            BdBarcodeStore barcodeStore = new BdBarcodeStore();
                            barcodeStore.FId = GuidUtils.getGuid();
                            barcodeStore.FParentId = receiveOrder.FId;
                            barcodeStore.FProductId = receiveDetail.BdProduct == null ? null : receiveDetail.BdProduct.FId;
                            barcodeStore.FBarcode = DateUtils.GetCurDateFormat("yyMMddHHmmssffff");
                            barcodeStore.FStatus = ConstData.BARCODE_STATUS_NO;
                            barcodeStore.BdProduct = receiveDetail.BdProduct;

                            barcodeList.Add(barcodeStore);
                        }
                    }

                    Report report = new Report();
                    string templateFilePath = @"" + serverPath + "Upload\\Report\\barcode_new.frx";

                    long s = 0L;
                    foreach (BdBarcodeStore barcodeStore in barcodeList)
                    {
                        string FProductId = barcodeStore.FProductId;

                        report.Load(templateFilePath);

                        report.SetParameterValue("p_code", barcodeStore.BdProduct == null ? "" : barcodeStore.BdProduct.FNumber);
                        report.SetParameterValue("p_name", barcodeStore.BdProduct == null ? "" : barcodeStore.BdProduct.FName);
                        report.SetParameterValue("p_barcode", barcodeStore.FBarcode);

                        if (s == 0)
                        {
                            report.Prepare();
                        }
                        else
                        {
                            report.Prepare(true);
                        }

                        s++;
                        barcodeStore.BdProduct = null;
                        barcodeStore.FProductId = FProductId;
                    }

                    PDFExport export = new PDFExport();
                    report.Export(export, saveFilePath + fileName);
                    report.Dispose();

                    foreach (BdBarcodeStore barcodeStore in barcodeList)
                    {
                        receiveOrder.BdBarcodeStore.Add(barcodeStore);
                    }
                    receiveOrderDAO.Save();
                }

                response.ContentType = "application/pdf";
                response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.TransmitFile(saveFilePath + fileName);
            }
        }*/
    }
}